#!/usr/bin/python
# -*-coding:UTF-8 -*-
# ========================
# @Time  : 2021/3/5
# @Author: Sunny
# ========================

# 这个monkey及为所有模块打包，这块代码官方文档是建议写在最上方
# 有monkey以后，系统只要遇到IO操作，耗时等待，都会自动切换
from gevent import monkey

monkey.patch_all()
import requests
import time
import gevent

"""
gevent模块对greenlet有做了一层封装，当程序遇到耗时等待的时候，会进行自动切换

gevent中默认是遇到gevent中的sleep()会进行自动切换

如果让gevent遇到IO自动切换，需要在程序的导包处加一个monkey.patch_all()补丁，
monkey.patch_all()补丁不支持多线程，开多个线程会报错

"""


# def work1():
#     for i in range(6):
#         gevent.sleep(1)
#         print(f'浇花的第{i+1}')
#
#
# def work2():
#     for i in range(5):
#         gevent.sleep(1)
#         print(f'打墙的第{i+1}')
#
#
# # 创建了2个协程
# g1 = gevent.spawn(work1)
# g2 = gevent.spawn(work2)


# g1.join()
# # g2.join()


# -----------------------------------------------------------------------

# 定义装饰器
def decorator(func):
    def wrapper(*args):
        # 获取程序执行前的时间
        start = time.time()
        # 执行功能程序
        func(*args)
        # 获取程序执行后的时间
        end = time.time()
        print(f'程序的执行时间为:{end - start}')
        return end - start

    return wrapper


# def work2():
#     for i in range(5):
#         #gevent中默认是遇到gevent中的sleep()会进行自动切换
#         gevent.sleep(1)
#         print(f'打墙的第{i+1}')


# 如果创建5000个协程访问10000个请求
urls = (f'https://www.baidu.com---{i}' for i in range(10000))


def work2():
    while True:
        try:
            url = next(urls)
        except StopIteration:
            break
        else:
            time.sleep(1)  # 因为加了monkey，所以也可以切换
            print(f'正在请求url:{url}')


@decorator
def main():
    cos = []
    for i in range(10000):
        cor = gevent.spawn(work2)
        cos.append(cor)

    for i in cos:
        i.join()


main()
